import Vue from 'vue'
import '@/views/approval/index'
import { ACCESS_TOKEN, USER_INFO, USER_NAME } from '@/store/mutation-types'
import { getAction, postAction } from '@/api/manage'
import { Modal } from 'ant-design-vue'
export const FlowMixin = {
  data() {
    return {
      currentUser: Vue.ls.get(USER_INFO).username,
      showPrintBtn: false,
      hiddenTaskDefKey: '',
      messageId: '', // 工作台URL里面的msgId参数
      options: {
        request: {
          baseUrl: this.API_BASE_URL, // 业务系统根路径
          timeOut: 20000, // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token'] = Vue.ls.get(ACCESS_TOKEN)
            return config
          },
        },
        userId: Vue.ls.get(USER_NAME),
      },
      historyDialog: {
        // 审批历史模态框属性
      },
      tips: '',
      showRelationUserTips: false,
      custom: {},
      param: {},
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper',
        },
      ],
      urls: {
        getProcess: '/workReport/payment/getProcess',
        loadTask: '/flow/api/process/current/user/task?processInstanceId=',
        getFlowElements: '/flow/api/process/all/element',
        comments: '/flow/api/comment/list',
        notifys: '/flow/api/bpm/notify/list',
      },
      process: { taskDefKey: '' },
      currentTask: {},
      flowElements: [],
      showProgress: true,
      comments: [],
      notifys: [],
      approvalLoading: false,
      flowId: '',
      flowTask:{},
    }
  },
  computed: {
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    },
  },
  mounted() {},
  methods: {
    init() {},
    handlerOk() {
      this.$refs.childrenRef.submitTaskNotBefore()
      this.showRelationUserTips = false
    },
    afterSubmit(res) {
      this.approvalLoading = false
      if (this.doPass(res)) {
        return true
      } else {
        return false
      }
    },
    beforeReject(res) {
      // 驳回前置动作
      if (this.checkOptionValue()) {
        if (this.doNotPass()) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    async doPass(res) {
      let flag = true
      this.fetchProcess(this.flowId)
      return flag
    },
    async doNotPass() {
      let flag = true
      this.fetchProcess(this.flowId)
      return flag
    },
    async doBack() {
      let flag = true
      this.fetchProcess(this.flowId)
    },
    async doCancel() {
      var flag = false
      this.fetchProcess(this.flowId)
      return flag
    },
    checkOptionValue() {
      var options = this.$refs.childrenRef.data
      if (options == '' || options == null || options == undefined) {
        return false
      } else {
        return true
      }
    },
    async afterReject(res) {
      let flag = true
      // setTimeout(this.init(), 3000)
      return flag
    },
    //退回
    backAction(res) {
      if (this.doBack()) {
        this.$messageWorkReport.success('退回成功')
      }
    },
    //撤回后
    afterCancelSubmit() {
      if (this.doCancel()) {
        this.$messageWorkReport.success('撤回成功')
      }
    },
    // 生成抄送任务方法，非必须
    sendNotify() {
      // 参数一：抄送人，参数二：工作台打开详情链接
      this.$refs.childrenRef.saveBpmNotify('liangyh', 'http://xxxxx.com')
    },
    saveNotifyOpinion() {
      // 保存抄送意见前置动作
      debugger
      return true
    },
    print() {},
    async fetchProcess(flowId) {
      if (flowId) {
        this.flowId = flowId
        this.getFlowElements(flowId)
        let res = await getAction(this.urls.getProcess + '/' + flowId, {})
        if (res.success) {
          this.process = res.result
          this.currentTask = res.result
          if (!this.process) {
            this.process = { taskDefKey: '' }
          }
        } else {
          this.$messageWorkReport.error(res.message)
        }
      }
    },
    getFlowElements(flowId) {
      getAction(this.urls.getFlowElements + '?processInstanceId=' + flowId, {}).then((res) => {
        if (res.success && res.data) {
          this.flowElements = res.data
        } else {
          this.$messageWorkReport.error(res.message)
        }
      })
    },
    taskLoad(task) {
      this.flowTask = task
      // 当前任务加载回调函数，获取当前任务信息
      if (task) {
        this.getFlowElements(task.processInstanceId)
      }

      this.currentTask = task
    },
    checkCurrentTaskUser(taskDefKeys = []) {
      if (this.currentTask) {
        return (
          this.checkCurrentTask(taskDefKeys) &&
          this.currentTask &&
          this.currentTask.currentUserId &&
          this.currentTask.currentUserId.split(',').indexOf(this.currentUser) > -1
        )
      } else {
        setTimeout(this.checkCurrentTaskUser(taskDefKeys, stepTaskDefKeys), 3000)
      }
    },
    checkCurrentUser(taskDefKeys = []) {
      if (this.currentTask) {
        return (
          this.currentTask &&
          this.currentTask.currentUserId &&
          this.currentTask.currentUserId.split(',').indexOf(this.currentUser) > -1
        )
      }
    },
    checkCurrentTask(taskDefKeys = [], stepTaskDefKeys = []) {
      if (this.currentTask) {
        if (stepTaskDefKeys) {
          taskDefKeys = [...taskDefKeys, ...stepTaskDefKeys]
        }
        return taskDefKeys.indexOf(this.process.taskDefKey) > -1
      } else {
        setTimeout(this.checkCurrentTask(taskDefKeys, stepTaskDefKeys), 3000)
      }
    },
    async getTask(flowId) {
      if (flowId) {
        this.getFlowElements(flowId)
        let res = await getAction(this.urls.loadTask + flowId + '&taskId=', {})
        if (res.success) {
          this.currentTask = res.result
          this.process = res.result
        } else {
          this.$messageWorkReport.error(res.message)
        }
      }
    },
    checkFlowElement(taskDefKeys = []) {
      if (this.flowElements) {
        let flag = 0
        for (let taskDefKey of taskDefKeys) {
          for (let element of this.flowElements.flowElementVoList) {
            if (element.id == taskDefKey) {
              flag++
            }
          }
        }
        if (flag == taskDefKeys.length > 0) {
          return true
        } else {
          return false
        }
      } else {
        setTimeout(this.checkFlowElement(taskDefKeys), 3000)
      }
    },
    async fetchFlowComments(processInstanceId) {
      let res = await postAction(this.urls.comments + '?processInstanceId=' + processInstanceId + '&taskType=0')
      if (res.success) {
        this.comments = res.data
      }
    },
    async fetchFlowNotifys(processInstanceId) {
      let res = await getAction(this.urls.notifys + '?processInstanceId=' + processInstanceId + '&taskType=0')
      if (res.success) {
        this.notifys = res.data
      }
    },
    closeSelectedTag(view, flowId, msg) {
      // let that = this
      //   getAction(this.urls.loadTask + flowId + '&taskId=', {}).then((res) => {
      //     this.currentTask = res.data
      //     if (!res.data || res.data.currentUserId != this.currentUser) {
      //       if(this.visitedViews.length==1){
      //         Modal.confirm({
      //           title: '流程提醒',
      //           content: msg+'是否关闭审批页面，关闭请点击【确认】，保留审批页面请点击【取消】',
      //           wrapClassName: 'approvalBox',
      //           onOk() {
      //             that.toCloseTab(view)
      //           },
      //           onCancel() {},
      //         })
      //       }else{
      //         this.$messageWorkReport.success(msg+",页面将自动关闭", 10)
      //         this.toCloseTab(view)
      //       }
      //     }
      //   })
    },
    toCloseTab(view) {
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        if (this.isActive(view)) {
          const latestView = visitedViews.slice(-1)[0]
          if (latestView) {
            this.$router.push(latestView)
          } else {
            if (view.fullPath == this.$route.fullPath) {
              this.$router.push('/')
            } else {
              this.$router.push(this.$route.fullPath)
            }
          }
        }
        //关闭单个
        Bus.$emit('removeCache', 'closeSelectedTag', view)
      })
    },
    refreshSelectedTag(view) {
      this.$store.dispatch('tagsView/delCachedView', view).then(() => {
        const { fullPath } = view
        this.$nextTick(() => {
          this.$router.replace({
            path: '/redirect' + fullPath,
          })
        })
        // 移除redirect组件缓存
        Bus.$emit('removeRedirect', view)
        //关闭单个
        Bus.$emit('removeCache', 'closeSelectedTag', view)
      })
    },
    isActive(route) {
      return route.fullPath === this.$route.fullPath
    },
  },
}
